// cloudfunctions/addBill/index.js
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

/**
 * 添加账单云函数
 */
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID

  try {
    const {
      type,
      amount,
      category,
      categoryId,
      date,
      time,
      note,
      tags,
      location,
      images
    } = event

    // 参数验证
    if (!type || !['income', 'expense'].includes(type)) {
      return {
        success: false,
        code: 1001,
        message: '账单类型无效'
      }
    }

    if (!amount || typeof amount !== 'number' || amount <= 0 || amount > 999999.99) {
      return {
        success: false,
        code: 1001,
        message: '金额必须是0-999999.99之间的数字'
      }
    }

    if (!category || typeof category !== 'string') {
      return {
        success: false,
        code: 1001,
        message: '分类不能为空'
      }
    }

    if (!date || !/^\d{4}-\d{2}-\d{2}$/.test(date)) {
      return {
        success: false,
        code: 1001,
        message: '日期格式无效'
      }
    }

    if (!time || !/^\d{2}:\d{2}$/.test(time)) {
      return {
        success: false,
        code: 1001,
        message: '时间格式无效'
      }
    }

    // 验证分类是否存在
    if (categoryId) {
      const categoryQuery = await db.collection('categories').doc(categoryId).get()
      if (!categoryQuery.data) {
        return {
          success: false,
          code: 2002,
          message: '分类不存在'
        }
      }
    }

    // 获取用户信息
    const userQuery = await db.collection('users').where({
      _openid: openid
    }).get()

    if (userQuery.data.length === 0) {
      return {
        success: false,
        code: 1002,
        message: '用户不存在'
      }
    }

    const user = userQuery.data[0]
    const currentTime = new Date()

    // 构建账单数据
    const billData = {
      _openid: openid,
      userId: user._id,
      type: type,
      amount: Number(amount.toFixed(2)), // 保留2位小数
      category: category,
      categoryId: categoryId || '',
      date: date,
      time: time,
      note: note || '',
      tags: tags || [],
      location: location || null,
      images: images || [],
      createTime: currentTime,
      updateTime: currentTime,
      isDeleted: false,
      syncStatus: 'synced',
      version: 1
    }

    // 添加账单
    const addResult = await db.collection('bills').add({
      data: billData
    })

    // 更新用户统计信息
    const updateData = {
      'statistics.totalBills': db.command.inc(1),
      'statistics.lastBillDate': date,
      updateTime: currentTime
    }

    if (type === 'income') {
      updateData['statistics.totalIncome'] = db.command.inc(amount)
    } else {
      updateData['statistics.totalExpense'] = db.command.inc(amount)
    }

    await db.collection('users').doc(user._id).update({
      data: updateData
    })

    // 更新分类使用统计
    if (categoryId) {
      await db.collection('categories').doc(categoryId).update({
        data: {
          usageCount: db.command.inc(1),
          lastUsedTime: currentTime
        }
      })
    }

    // 检查预算使用情况（如果是支出）
    let budgetWarning = null
    if (type === 'expense') {
      const month = date.substring(0, 7) // YYYY-MM
      const budgetQuery = await db.collection('budgets').where({
        _openid: openid,
        month: month,
        isActive: true
      }).get()

      if (budgetQuery.data.length > 0) {
        const budget = budgetQuery.data[0]
        const newSpent = budget.spent + amount
        const newUsageRate = (newSpent / budget.amount) * 100

        // 更新预算使用情况
        await db.collection('budgets').doc(budget._id).update({
          data: {
            spent: newSpent,
            remaining: budget.amount - newSpent,
            usageRate: newUsageRate,
            updateTime: currentTime
          }
        })

        // 检查是否需要预警
        if (newUsageRate >= 100) {
          budgetWarning = {
            type: 'exceeded',
            message: '本月预算已超支'
          }
        } else if (newUsageRate >= 80) {
          budgetWarning = {
            type: 'warning',
            message: `本月预算已使用${newUsageRate.toFixed(1)}%`
          }
        }
      }
    }

    const responseData = {
      _id: addResult._id,
      ...billData
    }

    if (budgetWarning) {
      responseData.budgetWarning = budgetWarning
    }

    return {
      success: true,
      code: 0,
      message: '账单添加成功',
      data: responseData
    }

  } catch (error) {
    console.error('添加账单失败:', error)
    return {
      success: false,
      code: 5001,
      message: '添加账单失败，请重试',
      error: error.message
    }
  }
}